<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <base href="/">
    <meta charset="UTF-8">
    <title>商品管理</title>
    <link rel="stylesheet" href="layui/css/layui.css">
    <style>
        /* 新增表格容器样式 */
        .table-container {
            overflow: hidden;
            margin: 15px;
        }
        .layui-table tr{
            height: auto;
        }
        /* 单元格自适应高度 */
        .layui-table-cell {
            height: auto !important;
            min-height: 52px;
            white-space: normal;
            padding: 8px 10px;
            line-height: 1.5;
            display: flex;
            align-items: center;
        }
        /* 操作按钮样式 */
        .layui-table-tool .layui-btn {
            margin: 2px;
            padding: 0 8px;
            height: 28px;
            line-height: 28px;
        }
        /* 操作按钮容器样式 */
        .layui-table-tool-temp {
            padding: 5px 0 !important;
        }
        /* 按钮统一样式 */
        .layui-table .layui-btn {
            min-width: 50px;
            height: 28px;
            line-height: 28px;
            padding: 0 8px;
            font-size: 12px;
            border-radius: 3px;
            white-space: nowrap;
        }
        /* 鼠标悬停效果 */
        .layui-table .layui-btn:hover {
            opacity: 0.9;
            transform: translateY(-1px);
        }

        /* 固定列样式覆盖 */
        .layui-table-fixed {
            box-shadow: -2px 0 6px rgba(0,0,0,.08);
        }
        /* 操作列按钮容器样式 */
        .layui-btn-container {
            display: flex;
            align-items: center;
        }
    </style>
</head>
<body>
<!--数据列表-->
<div class="table-container">
    <table class="layui-table" lay-data="{
            url:'product/list',
            page:true,
            id:'datalist',
            toolbar:'#toptools',
            scrollX: true,
            parseData: function(res){
                return {
                    code: res.code,
                    msg: res.msg,
                    count: res.count,
                    data: res.data
                };
            }
        }" lay-filter="datalist">
        <thead>
        <tr>
            <th lay-data="{field:'productid', width:100}">ID</th>
            <th lay-data="{field:'productname', width:150}">名称</th>
            <th lay-data="{field:'productcategory', width:150}">一级分类</th>
            <th lay-data="{field:'productcategory2', width:150}">二级分类</th>
            <th lay-data="{templet:'#imgTpl', width:120}">图片</th>
            <th lay-data="{field:'stock', width:100}">库存</th>
            <th lay-data="{field:'sales', width:100}">销量</th>
            <th lay-data="{field:'price', width:100}">价格</th>
            <th lay-data="{field:'oldprice', width:100}">原价</th>
            <th lay-data="{templet:'#stateTpl', width:100}">状态</th>
            <th lay-data="{field:'description', width:200}">描述</th>
            <th lay-data="{toolbar:'#linetools', width:180, fixed: 'right'}">操作</th>
        </tr>
        </thead>
    </table>
</div>

<!--图片列自定义模板-->
<script type="text/html" id="imgTpl">
    <!--src属性中就要写上当前行的imgurl属性-->
    <img src="{{d.imgurl}}" style="height: 50px;width: 50px;">
</script>

<!--状态列自定义模板-->
<script type="text/html" id="stateTpl">
    {{# if (d.isdel === 1) { }}
    已下架
    {{# } else if (d.stock > 0) { }}
    <span style="color: green;">有货</span>
    {{# } else { }}
    <span style="color: red;">缺货</span>
    {{# } }}
</script>

<!--新增数据表单-->
<div style="display:none" id="addWin" lay-filter="addWin" class="layui-form">
    <div class="layui-form-item">
        <label class="layui-form-label">一级分类</label>
        <div class="layui-input-inline">
            <select _id="productcategory" lay-filter="productcategory" name="productcategory">
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">二级分类</label>
        <div class="layui-input-inline">
            <select _id="productcategory2" name="productcategory2">
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">名称</label>
        <div class="layui-input-inline">
            <input type="text" name="productname" required lay-verify="required" placeholder="请输入名称" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">库存</label>
        <div class="layui-input-inline">
            <input type="text" name="stock" required lay-verify="required" placeholder="请输入库存数量" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">销量</label>
        <div class="layui-input-inline">
            <input type="text" name="sales" required lay-verify="required" placeholder="请输入销量" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">价格</label>
        <div class="layui-input-inline">
            <input type="text" name="price" required lay-verify="required" placeholder="请输入价格" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">原价</label>
        <div class="layui-input-inline">
            <input type="text" name="oldprice" required lay-verify="required" placeholder="请输入原价" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">描述</label>
        <div class="layui-input-inline">
            <input type="text" name="description" required lay-verify="required" placeholder="请输入商品描述" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">图片</label>
        <div class="layui-input-inline">
            <img src="easyfile/upload.jpeg" _id="addupload" style="width: 100px;height: 100px;cursor: pointer">
            <input type="hidden" _id="addimgurl" name="imgurl" lay-verify="easyimg">
        </div>
    </div>
    <div class="layui-form-item">
        <button type="button" lay-submit lay-filter="addsave" class="layui-btn" id="addsave">保存</button>
        <button type="button" class="layui-btn" id="addcancel">取消</button>
    </div>
</div>

<!--修改对话框-->
<div style="display:none" id="editWin" lay-filter="editWin" class="layui-form">
    <input name="productid" type="hidden">
    <div class="layui-form-item">
        <label class="layui-form-label">一级分类</label>
        <div class="layui-input-inline">
            <select _id="productcategory" lay-filter="productcategory" name="productcategory">
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">二级分类</label>
        <div class="layui-input-inline">
            <select _id="productcategory2" name="productcategory2">
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">名称</label>
        <div class="layui-input-inline">
            <input type="text" name="productname" required lay-verify="required" placeholder="请输入名称" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">库存</label>
        <div class="layui-input-inline">
            <input type="text" name="stock" required lay-verify="required" placeholder="请输入库存数量" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">销量</label>
        <div class="layui-input-inline">
            <input type="text" name="sales" required lay-verify="required" placeholder="请输入销量" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">价格</label>
        <div class="layui-input-inline">
            <input type="text" name="price" required lay-verify="required" placeholder="请输入价格" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">原价</label>
        <div class="layui-input-inline">
            <input type="text" name="oldprice" required lay-verify="required" placeholder="请输入原价" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">描述</label>
        <div class="layui-input-inline">
            <input type="text" name="description" required lay-verify="required" placeholder="请输入商品描述" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">图片</label>
        <div class="layui-input-inline">
            <img src="easyfile/upload.jpeg" _id="addupload" style="width: 100px;height: 100px;cursor: pointer">
            <input type="hidden" _id="addimgurl" name="imgurl" lay-verify="easyimg">
        </div>
    </div>
    <div class="layui-form-item">
        <button type="button" lay-submit lay-filter="editsave" class="layui-btn">保存</button>
        <button type="button" class="layui-btn" id="editcancel">取消</button>
    </div>
</div>

<!--行内工具栏-->
<script id="linetools" type="text/html">
    <div class="layui-btn-container" style="height:52px">
        <button class="layui-btn layui-btn-sm" lay-event="edit">编辑</button>
        <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="delete">删除</button>
    </div>
</script>
<!--头部工具栏-->
<script id="toptools" type="text/html">
    <div class="layui-form-item">
        <div class="layui-input-inline">
            <input type="text" name="text"  placeholder="请输入查询内容" autocomplete="off" class="layui-input">
        </div>
        <div class="layui-input-inline">
            <button type="button" class="layui-btn" lay-event="check">查询</button>
            <button type="button" class="layui-btn" lay-event="add">新增</button>
        </div>
    </div>
</script>

<script src="layui/layui.all.js"></script>
<script>
    const $ = layui.$;
    const table = layui.table;
    const form = layui.form;
    const layer = layui.layer;
    const upload = layui.upload;
    let addIndex;
    let editIndex;

    // 获取商品数据
    function getProducts() {
        $.ajax({
            url: 'product/list',
            success: function (result) {
                if (result && result.data) {
                    const allProducts = result.data;
                    table.reload("datalist", {
                        data: allProducts
                    });
                } else {
                    console.error('返回的数据格式不正确:', result);
                    layer.msg('返回的数据格式不正确，请稍后重试', { icon: 2 });
                }
            },
            error: function (error) {
                console.error('获取商品列表失败:', error);
                layer.msg('获取商品列表失败，请稍后重试', { icon: 2 });
            }
        });
    }
    // 页面加载时获取商品数据
    getProducts();

    // 头部按钮监听事件
    table.on("toolbar(datalist)", function (obj) {
        let event = obj.event;
        if (event === 'add') {
            let addIndex = layer.open({
                type: 1,
                title: '新增商品',
                area: ['400px', '400px'],
                content: $("#addWin")
            });
            // 绑定新增取消按钮事件
            $('#addcancel').on('click', function () {
                layer.close(addIndex);
            });
        } else if (event === 'check') {
            // 获取输入框中的数据
            let text = $("[name='text']").val();
            // 发送到后端 layui表格加载
            getProducts();
            table.reload("datalist", {
                where: { text: text },
                page: { curr: 1 }
            });
        }
    });

    // 行内按钮监听事件
    table.on("tool(datalist)", function (obj) {
        // 被点击按钮的lay-event属性值
        let event = obj.event;
        // 被点击按钮所在行的数据
        let data = obj.data;
        if (event === 'delete') {
            // 防止误操作
            layer.confirm("确认要删除吗？", function () {
                // 点击确认后要执行的代码
                console.log(data);
                $.ajax({
                    url: 'product/delete',
                    data: { id: data.productid },
                    success: function () {
                        // 提示信息
                        layer.msg("删除成功", { time: 1800, icon: 1 });
                        // 刷新表格信息
                        getProducts();
                    }
                });
            });
        } else if (event === 'edit') {
            // 回显表单数据
            form.val("editWin", data);
            // 回显图片
            $("[_id='addupload']").attr("src", data.imgurl);
            let editIndex = layer.open({
                type: 1,
                title: '编辑商品',
                area: ['400px', '400px'],
                content: $("#editWin")
            });
            // 绑定编辑取消按钮事件
            $('#editcancel').on('click', function () {
                layer.close(editIndex);
            });
        }
    });

    // 商品分类下拉事件
    function getChildren(id) {
        var datalist;
        $.ajax({
            url: "category/getChildren",
            data: { id: id },
            async: false,
            success: function (result) {
                console.log(result);
                datalist = result;
            }
        });
        return datalist;
    }

    // 二级分类选择事件
    function showitems(id, element) {
        let datalist = getChildren(id);
        let $elem = $(element);
        $elem.empty();
        $elem.append(
            "<option value=''></option>"
        );
        for (let i = 0; i < datalist.length; i++) {
            $elem.append(
                "<option value='" + datalist[i].categoryid + "'>" + datalist[i].categoryname + '</option>'
            );
        }
        form.render("select");
    }

    // 监听一级分类的改变事件
    form.on('select(productcategory)', function (data) {
        let val = data.value;
        showitems(val, '[_id="productcategory2"]');
    });

    // 浏览器刚开始就加载的数据一级分类
    showitems(-1, "[_id='productcategory']");

    // 文件上传
    upload.render({
        elem: "[_id='addupload']",
        url: "file/upload",
        done: function (result) {
            console.log(result.data[0].src);
            let url = result.data[0].src;
            $("[_id='addupload']").attr("src", url);
            $("[_id='addimgurl']").val(url);
        },
        error: function () {
            layer.msg("上传失败", { icon: 2 });
        }
    });

    // 新增保存提交按钮事件
    form.on("submit(addsave)", function (data) {
        let field = data.field;
        console.log("--表单提交，并验证通过--");
        console.log(data.field);
        // 获取一级分类的名称
        field.productcategory = $('[_id="productcategory"] option:selected').text();
        // 获取二级分类的名称
        field.productcategory2 = $('[_id="productcategory2"] option:selected').text();
        console.log("新增表单的数据", data);
        // 提交ajax提交数据
        $.ajax({
            url: 'product/add',
            data: data.field,
            success: function (result) {
                // 关闭掉本窗口
                layer.closeAll();
                // 提示成功
                layer.msg("添加成功", { icon: 1, time: 1800 });
                // 刷新表格
                getProducts();
            }
        });
        return false; // 禁止表单提交
    });

    // 绑定新增取消按钮事件
    $('#addcancel').on('click', function () {
        layer.close(addIndex);
    });

    form.on("submit(editsave)", function (data) {
        let field = data.field;
        // 获取一级分类的名称
        field.productcategory = $('[_id="productcategory"] option:selected').text();
        // 获取二级分类的名称
        field.productcategory2 = $('[_id="productcategory2"] option:selected').text();
        console.log("编辑表单的数据", data);
        // data.field 表单数据
        $.ajax({
            url: "product/edit",
            data: data.field,
            success: function () {
                // 关闭掉本窗口
                layer.closeAll();
                // 提示成功
                layer.msg("修改成功", { icon: 1, time: 1800 });
                // 刷新表格
                getProducts();
            }
        });
        return false;
    });

    // 绑定编辑取消按钮事件
    $('#editcancel').on('click', function () {
        layer.close(editIndex);
    });

    /*自定义表单规范*/
    form.verify({
        easyimg: function (value, item) {
            // value  表单组件中填入的值
            // item   对应的表单组件
            if (!value) {
                return "必须上传图片";
            }
        }
    });
</script>
</body>
</html>